package com.user.service.impl;

import com.aliyuncs.exceptions.ClientException;
import com.user.comment.KeyStr;
import com.user.config.JwtProperties;
import com.user.entity.*;
import com.user.mapper.UserMapper;
import com.user.service.UserService;
import com.user.util.JedisUtil;
import com.user.util.JwtUtils;
import com.user.util.NumberUtils;
import com.user.util.SMSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

import static com.user.comment.KeyStr.SECONDS;

@Service
public class UserServiceImpl implements UserService{
    @Autowired
    private JwtProperties prop;
    @Resource
    private UserMapper userMapper;
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
    @Override
    public boolean checkData(String data, Integer type) {
        User user = new User();
        switch (type){
            case 1:
                user.setUsername(data);
                break;
            case 2:
                user.setPhone(data);
                break;
        }
        int i = userMapper.selectCount(user);
        return i==0;
    }

    @Override
    public String sendeCode(String phone) {
        String code = NumberUtils.generateCode(6);
        boolean flag= false;
        try {
            flag =SMSUtils.sendShortMessage(SMSUtils.CODE,phone,code);
        } catch (ClientException e) {
            e.printStackTrace();
            System.out.println("短信发送接口异常!!!");
            code ="短信发送失败!!";
        }
        if (flag){
            Jedis jedis = JedisUtil.getJedis();
            jedis.setex(KeyStr.SMS+phone,SECONDS,code);
            JedisUtil.close(jedis);
        }
        return code;
    }

    @Override
    public boolean register(User user, String code) {
        Jedis jedis = JedisUtil.getJedis();
        String redisCode = jedis.get(KeyStr.SMS + user.getPhone());
        JedisUtil.close(jedis);
        if (!Objects.equals(code,redisCode)){
            return false;
        }
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        int count = userMapper.insert(user);
        return count == 1;
    }

    @Override
    public ResultBody queryUserByName(String username, String password) {
        User user = new User();
        user.setUsername(username);
        user = userMapper.selectOne(user);
        boolean matches = passwordEncoder.matches(password, user.getPassword());
        return ResultBody.creatResult(200,matches,matches?"登录成功":"失败");
    }

    @Override
    public String login(String username, String password) {
        User user = new User();
        user.setUsername(username);
        user = userMapper.selectOne(user);
        boolean matches = passwordEncoder.matches(password, user.getPassword());
        String token=null;
        if (matches == true){
            HashSet<Role> hashSet =  new HashSet<>();
            hashSet.add(new Role("管理员"));
            UserInfo userInfo = new UserInfo(user.getId(), user.getUsername(),"",hashSet);
            token= JwtUtils.generateTokenExpireInSeconds(userInfo, prop.getPrivateKey(), prop.getTokenProper().getExpire());
        }
        return token;
    }

    @Override
    public Payload<UserInfo> verifyUser(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        String token=null;
        for (Cookie cookie : cookies) {
            if(Objects.equals(cookie.getName(),prop.getTokenProper().getCookieName())){
                token =cookie.getValue();
                break;
            }
        }
        Payload<UserInfo> infoFromToken = JwtUtils.getInfoFromToken(token, prop.getPublicKey(), UserInfo.class);
        return infoFromToken;
    }

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        String token=null;
        for (Cookie cookie : cookies) {
            if(Objects.equals(cookie.getName(),prop.getTokenProper().getCookieName())){
                token =cookie.getValue();
                break;
            }
        }
        Payload<UserInfo> infoFromToken = JwtUtils.getInfoFromToken(token, prop.getPublicKey(), UserInfo.class);
        Date expiration = infoFromToken.getExpiration();
        long time = expiration.getTime() - System.currentTimeMillis();
        System.out.println("剩余时间："+time);
        Cookie cookie = new Cookie(prop.getTokenProper().getCookieName(), "");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
    }
}
